{template 'header'}
<div class="box" style="display: flex;height: 100%;">

    <div class="item" style="flex: 1;text-align: center;padding-top: 88px;">
        <div class="edit-box" style="display: none;">
            <div class="jiao"></div>
            <form class="edit-form" style="max-height: 560px;overflow: auto;">
                <div class="panel-group" id="accordion" role="tablist" aria-multiselectable="true" style="padding: 15px;" data-module="good-class">

                </div>
                <button type="button" class="btn btn-primary btn-lg add-name" onclick="addNewItem()" style="background: #333 !important;border: 0;border-radius: 5px;font-size: 14px;padding: 11px 35px;">  </button>
                <div style="position: absolute;bottom: 0px;text-align: center;width: 100%;height: 40px;background: #f7f7f7;font-size: 0;">
                    <button type="button" onclick="goSubmit()" class="btn btn-default" style="border: 0 !important;background: none !important;text-align: center;width: 50%;border-right: 1px solid #dedede!important;line-height: 40px;padding: 0;">保存</button>
                    <button type="button" onclick="closeEdit()" class="btn btn-default" style="border: 0 !important;background: none !important;text-align: center;width: 50%;border-right: 1px solid #dedede!important;line-height: 40px;padding: 0;">取消</button>
                </div>
            </form>
        </div>

        <div class="diy-phone" data-merch="0" style="display: inline-block;">
            <div class="phone-head"></div>
            <div class="phone-body" style="width: 320px;height: 520px;overflow: auto;">
                <div class="phone-main ui-sortable dd" id="phone" style="background-color: rgb(250, 250, 250);">

                </div>
            </div>
            <div class="phone-foot"></div>
        </div>
    </div>

    <div class="right-box">
        <div class="right-title">
            <div class="title-word" ><span class="glyphicon glyphicon-th-large"></span>模板</div>
        </div>
        <div class="right-template">
            <div class="mould-title" style="padding: 10px;">

                <style>
                    .mould-title span{
                        margin: 0 5px 5px 0;
                        padding: 5px 10px;
                        font-size: 12px;
                    }
                    .mould-title span:nth-child(5n+1){
                        margin-right: 0;
                    }
                </style>

                <span class="btn btn-default" style="background: #24303C !important;border: 1px solid #24303C !important;color: #fff !important;">全部</span>
                <!--<span class="btn btn-default">旅游</span>
                <span class="btn btn-default">房产</span>
                <span class="btn btn-default">婚纱摄影</span>
                <span class="btn btn-default">官网</span>
                <span class="btn btn-default">汽车</span>-->
            </div>
            <ul class="page-list">
                <li page-id="base"><span class="glyphicon glyphicon-ok"></span><img src="{php echo MODEL_LOCAL}/template/tpl/base/home.jpg" alt=""><span class="bottom-word">莫奈微官网</span></li>
                <li page-id="hunsha"><span class="glyphicon glyphicon-ok"></span><img src="{php echo MODEL_LOCAL}/template/tpl/hunsha/home.png" alt=""><span class="bottom-word">莫奈婚纱摄影</span></li>
                <li page-id="jingqu"><span class="glyphicon glyphicon-ok"></span><img src="{php echo MODEL_LOCAL}/template/tpl/jingqu/home.png" alt=""><span class="bottom-word">莫奈婚纱摄影</span></li>
            </ul>
        </div>
        <style>
            .right-footer .btn,.right-template-footer .btn{
                width: 70px;
                text-align: center;
                padding: 5px;
            }
        </style>
    </div>
</div>

<script>
    /*
    *  箭头变化模块
    * */
    var confNow
    function listenChange() {
        $('.aitem').on('click', function (e) {

            $('.edit-box').show();
            if ( $(e.target).hasClass('aitem') ) {
                var modName = $(e.target).attr('data-module-name')

                $('.now').removeClass('now')
                $(e.target).addClass('now').siblings().removeClass('now')
                getHeight(e.target, 300)
            } else {
                var modName = $(e.target).parents('.aitem').attr('data-module-name')

                $('.now').removeClass('now')
                $(e.target).parents('.aitem').addClass('now').siblings().removeClass('now')
                getHeight($(e.target).parents('.aitem')[0], 300)
            }

            $('#accordion').attr('data-module', modName)
            var hasConponent = 0;
            for (var i = 0; i < confFile.length; i++) {
                if (confFile[i].name == modName) {
                    confNow = confFile[i]
                    hasConponent = 1;
                }
            }
            console.log(hasConponent)
            if (hasConponent) {
                getEditBox(confNow);
            } else {
                $('.edit-box').hide();
            }
        })

        $('.phone-body').scroll(function (e) {
            getHeight($('.now')[0], 10)
        })
    }

    function getHeight(n, time) {
        var boxH = $(n).offset().top - 225 + $(n).height()

        if (boxH > 520) {
            var h = $(n).offset().top - 225 + ($(n).height() - (boxH - 520)) / 2
        } else if ($(n).offset().top - 225 < 0) {
            var x = $(n).height() + ($(n).offset().top - 225)
            var h = x / 2
        } else {
            var h = $(n).offset().top - 225 + $(n).height() / 2
        }
        if (boxH > 670) {
            var h = 515
        } else if ($(n).offset().top - 225 < 0 - $(n).height()) {
            var h = -5
        }

        $('.jiao').animate({
            'top': 30 + h + 'px'
        }, time)
    }
</script>
<script>
    /*
    *  编辑数据时显示的绑定
    * */
    function bindInput() {
        $('.word-input').on('keyup',function (e) {
            var moduleClass = $(this).parents('.panel-group').attr('data-module');
            var index = $(this).parents('.panel-body').attr('data-index');

            $('.' + moduleClass + ' .word-in:eq(' + index + ')').text($(this).val() ? $(this).val() : '文本')
            for (var i = 0;i < confFile.length;i++) {
                if (confFile[i].name == moduleClass) {
                    confFile[i].data[index][confFile[i].textField] = $(this).val();
                }
            }
        })
    }
    function bindImg(elm) {
        // console.log($(elm).parent().siblings('.form-control').val())
        var moduleClass = $(elm).parents('.panel-group').attr('data-module');
        var index = $(elm).parents('.panel-body').attr('data-index');

        $('.' + moduleClass + ' .image-in:eq(' + index + ')').attr('src', 'http://vq.cn/attachment/' + $(elm).parent().siblings('.form-control').val() )

        for (var i = 0;i < confFile.length;i++) {
            if (confFile[i].name == moduleClass) {
                confFile[i].data[index][confFile[i].imageField] = 'http://vq.cn/attachment/' + $(elm).parent().siblings('.form-control').val();
            }
        }
    }

</script>

<script>
    /*
    *  按钮事件
    * */
    function closeEdit() {
        $('.edit-box').hide();
    }
    function goSubmit() {
        var moduleClass = $('#accordion').attr('data-module')
        var dataIndex;
        for (var i = 0;i < confFile.length;i++) {
            if (confFile[i].name == moduleClass) {
                dataIndex = i;
            }
        }
        $.ajax({
            url: confFile[dataIndex].setUrl,
            type: 'post',
            data: {
                data: confFile[dataIndex].data,
                delete: removeIdArr
            },
            dataType: 'json',
            success: function (data, status) {
                console.log(data)
                if (data.code == '200') {
                    alert('保存成功！')
                    removeIdArr = [];
                    $('.edit-box').hide();
                }
                /*alert('修改成功')
                $('.edit-box').hide();*/
            },
            fail: function (err, status) {
                console.log(err)
            }
        })
    }
</script>
<script>
    var rootUrl = '{php echo MODEL_LOCAL}'; // php解析模块路径
    var confFile;
    var confNum = [1, 1, 1];

    /*
   * 程序起点------------------------------
   * */
    initEdit('hunsha');
    
    function initEdit(path) {
        gethtml(path);
        getConf(path);
    }

    /**
     * 获取模块html
     * @method
     * @param {String} 模块路径
     * @return none
     **/
    function gethtml(path) {
        $.ajax({
            url: '{php echo MODEL_LOCAL}template/tpl/'+path+'/index.html',
            type: 'get',
            // data: $("form").serialize(),
            success: function (data, status) {
                var _html = data.replace(/{{rootUrl}}/g, rootUrl)
                $('.phone-main').html(_html)
                listenChange();
                $('.edit-box').hide();
            },
            fail: function (err, status) {
                console.log(err)
            }
        })
    }

    /**
     * 获取模块config
     * @method
     * @param {String} 模块路径
     * @return none
     **/
    function getConf(path) {
        $.ajax({
            url: rootUrl + 'template/tpl/'+ path +'/config.json',
            type: 'get',
            success: function (data, status) {
                confFile = data
                getModuleData()
            },
            fail: function (err, status) {
                console.log(err)
            }
        })
    }

    /*
    * 获取页面数据
    * */
    function getModuleData() {
        for(var i = 0; i < confFile.length; i++) {
            ajaxGetData(i);
        }
    }
    function ajaxGetData(i) {
        $.ajax({
            url: confFile[i].getUrl,
            type: 'POST',
            data: {
                num: confFile[i].limit
            },
            dataType: 'JSON',
            success: function (data, status) {
                confFile[i].data = data;
                setModuleData();
            },
            fail: function (err, status) {
                console.log(err)
            }
        })
    }

    /*
    * 将获取的数据加载到页面上
    * */
    var goShowFlag = 0;
    function setModuleData() {
        var _flag = 0; // 是否有未返回的数据
        for(var i = 0; i < confFile.length; i++) {
            if (confFile[i].data == '') {
                _flag = 1;
            }
        }
        if (_flag == 1) {

        } else {
            if (goShowFlag ==0) {
                goShowFlag=1;
                setTimeout(function () {
                    setThisData();
                }, 300)
            }
        }

    }

    /*
    * 添加新的组件
    * */
    function addNewItem() {
        var moduleClass = $('#accordion').attr('data-module');

        for (var i = 0;i < confFile.length;i++) {
            if (confFile[i].name == moduleClass) {
                if (confFile[i].limit <= $('#accordion .panel').length) {
                    alert('已到数量上限！');
                    return;
                }
                var newData = {}
                if (confFile[i].textField != '') {newData[confFile[i].textField] = ''}
                if (confFile[i].imageField != '') { newData[confFile[i].imageField] = ''}
                if (confFile[i].navField != '') { newData[confFile[i].navField] = ''}
                newData['sort'] = ''
                delete newData.id
                confFile[i].data.push(newData)
                setThisData();
                getEditBox(confFile[i]);
            }
        }
    }

    /*
    * 删除编辑组件
    * */
    var removeIdArr = [];
    function removeThisItem(e) {
        var moduleClass = $('#accordion').attr('data-module');
        var index = $(e.target).parents('.panel-heading').siblings('.panel-collapse').find('.panel-body').attr('data-index');

        for (var i = 0;i < confFile.length;i++) {
            if (confFile[i].name == moduleClass) {

                removeIdArr.push(confFile[i].data[index].id);
                confFile[i].data.splice(index, 1)[0]
                setThisData();
                getEditBox(confFile[i]);
            }
        }
    }
</script>

<script>
    /*
    * 获取edit组件
    * */
    function getEditBox(conf) {
        $.ajax({
            url: '{php echo MODEL_LOCAL}template/tpl/edit.html',
            type: 'get',
            success: function (data, status) {
                $('.edit-box form #accordion').html('');
                $('.add-name').text('添加' + confNow.disName)
                for (var i = 0; i < conf.data.length; i++) {
                    var _html = data.replace(/{{id}}/g, i).replace(/{{disName}}/g, confNow.disName + (i + 1))

                    var _data = $(_html).clone()

                    _data.find('.word-input').val(conf.data[i][conf.textField])

                    _data.find('.image-show').attr('src', conf.data[i][conf.imageField])
                    _data.find('.image-input').val(conf.data[i][conf.imageField])

                    _data.find('.nav-input').val(conf.data[i][conf.navField])

                    $('.edit-box form #accordion').append((_data))
                }

                $('.img-input-box,.word-input-box,.nav-input-box').hide()
                if (conf.conf[0]) { $('.img-input-box').show();}
                if (conf.conf[1]) { $('.word-input-box').show();}
                if (conf.conf[2]) { $('.nav-input-box').show();}

                bindInput();
            },
            fail: function (err, status) {
                console.log(err)
            }
        })
    }

</script>

<script type="text/javascript">
    /*
    *  选择图片事件
    * */
    function showImageDialog(elm, opts, options) {
        require(["util"], function(util){
            var btn = $(elm);
            var ipt = btn.parent().prev();
            var val = ipt.val();
            var img = ipt.parent().next().children();
            options = {'global':false,'class_extra':'','direct':true,'multiple':false,'fileSizeLimit':5120000};
            util.image(val, function(url){
                if(url.url){
                    if(img.length > 0){
                        img.get(0).src = url.url;
                        img.closest(".input-group").show();
                    }
                    ipt.val(url.attachment);
                    ipt.attr("filename",url.filename);
                    ipt.attr("url",url.url);
                }
                if(url.media_id){
                    if(img.length > 0){
                        img.get(0).src = "";
                    }
                    ipt.val(url.media_id);
                }


                bindImg(elm)
            }, options);
        });
    }
    function deleteImage(elm) {
        require(["jquery"], function($) {
            $(elm).prev().attr("src", "../addons/hs_cars/static/images/default-pic.jpg");
            $(elm).parent().prev().find("input").val("");

            bindImg(elm)
        });
    }
</script>

<script>
    /*
    * 获取当前正在使用的模板
    * */
        $.ajax({
            url: 'index.php?c=site&a=entry&m=hs_cars&do=web&r=other.index.getModules',
            type: 'GET',
            dataType: 'JSON',
            success: function (data, status) {
                var module_name = data.modules!=0 ? data.modules : 'base'
                initEdit(module_name)
                $('.page-list li').removeClass('choosed')
                $('.page-list li').each(function (i, n) {
                    if ($(n).attr('page-id') == module_name) {
                        $(n).addClass('choosed')
                    }
                })

            },
            fail: function (err, status) {
                console.log(err)
            }
        })
    /*
    * 选择新的模板
    * */
    $('.page-list li').on('click',function (e) {
        var module_name = $(this).attr('page-id')
        $(this).addClass('choosed').siblings('li').removeClass('choosed')
        $.ajax({
            url: 'index.php?c=site&a=entry&m=hs_cars&do=web&r=other.index.editModules',
            type: 'GET',
            dataType: 'JSON',
            data:{
                modules: module_name
            },
            success: function (data, status) {
                if (data.code == 200) {
                    initEdit(module_name)
                }
            },
            fail: function (err, status) {
                console.log(err)
            }
        })
    })
</script>
{template 'footer'}